package com.training.service;

import com.training.entity.TopicCategory;
import com.training.entity.TopicQuestion;
import com.training.entity.TopicQuestionComment;
import com.training.mapper.QaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class QaService {

    @Autowired
    private QaMapper qaMapper;

    // 创建问题
    public void createQuestion(TopicQuestion question) {
        if (!StringUtils.hasText(question.getTitle()) || question.getTitle().length() > 250) {
            throw new IllegalArgumentException("问题标题不能为空，且不能超过250个字符。");
        }
        qaMapper.createQuestion(question);
    }

    // 获取问题列表
    public List<TopicQuestion> getQuestions(String keyword) {
        return qaMapper.findQuestions(keyword);
    }

    // 获取问题详情
    public TopicQuestion getQuestionDetail(Long id) {
        qaMapper.incrementViewCount(id); // 增加浏览次数
        return qaMapper.findQuestionById(id);
    }

    // 获取问题的所有回答
    public List<TopicQuestionComment> getCommentsByQuestionId(Long questionId) {
        return qaMapper.findCommentsByQuestionId(questionId);
    }

    // 创建回答
    public void createComment(TopicQuestionComment comment) {
        if (!StringUtils.hasText(comment.getContent()) || comment.getContent().length() > 250) {
            throw new IllegalArgumentException("回答内容不能为空，且不能超过250个字符。");
        }
        qaMapper.createComment(comment);
    }

    // 采纳回答
    @Transactional
    public void adoptComment(Long questionId, Long commentId, Long questionOwnerId) {
        TopicQuestion question = qaMapper.findQuestionById(questionId);
        if (question == null || !question.getUserId().equals(questionOwnerId)) {
            throw new SecurityException("您无权采纳该问题的回答。");
        }
        if (question.getHasResolved() == 1) {
            throw new IllegalStateException("该问题已经采纳过回答了。");
        }

        qaMapper.markAsAdopted(commentId);
        qaMapper.markQuestionAsResolved(questionId);
    }

    // 获取所有分类
    public List<TopicCategory> getAllCategories() {
        return qaMapper.findAllCategories();
    }
    // 新增：获取用户提出的问题
    public List<TopicQuestion> getQuestionsAskedByUser(Long userId) {
        return qaMapper.findQuestionsByUserId(userId);
    }

    // 新增：获取用户回答过的问题
    public List<TopicQuestion> getQuestionsAnsweredByUser(Long userId) {
        return qaMapper.findQuestionsAnsweredByUserId(userId);
    }
}